package cn.hengzhu.main_manager.web.controller;

import cn.hengzhu.main_manager.repository.dao.CaseAdvertiseFileMapper;
import cn.hengzhu.main_manager.repository.dao.CaseAdvertiseMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCompMapper;
import cn.hengzhu.main_manager.repository.domain.*;
import cn.hengzhu.main_manager.repository.param.PageBaseParam;
import cn.hengzhu.main_manager.repository.vo.CaseAdvertiseVO;
import cn.hengzhu.main_manager.repository.vo.EditAdvertiseFileVO;
import cn.hengzhu.main_manager.utils.AjaxResult;
import cn.hengzhu.main_manager.utils.DateTimeHelper;
import cn.hengzhu.main_manager.utils.LayUiResultJson;
import cn.hengzhu.main_manager.utils.ToolsUtils;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.MoblieUrl;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/publish")
public class PublishAdvertisContorller {
	@Autowired
	private CaseAdvertiseMapper caseAdvertiseMapper;
	@Autowired
	private CaseAdvertiseFileMapper caseAdvertiseFileMapper;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private HttpServletRequest request;
	
	@MoblieUrl
	@RequestMapping("/index")
	public String login(Model model){
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		if(compId.equals(0)) {
			List<ManageComp> compList = manageCompMapper.selectByExample(new ManageCompExample());
			model.addAttribute("comps", compList);
		}
		model.addAttribute("compId", compId);
		return request.getAttribute("moblie")+"publish";
	}
/*	
	@RequestMapping("/ajax")
	@ResponseBody
	public List<String> ajax(String like){
		List<String> list = null;
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		if(like != null && like != "") {
			like = "%"+like+"%";
			List<CaseAdvertise> CaseAdvertiseList = null;
			if(compId==0) {
				CaseAdvertiseList = caseAdvertiseMapper.selectLikeDes(null, like);
			}else {
				CaseAdvertiseList = caseAdvertiseMapper.selectLikeDes(compId, like);
			}
			list = CaseAdvertiseList.stream().collect(Collectors.mapping(CaseAdvertise::getDes, Collectors.toList())).stream().distinct().collect(Collectors.toList());
		 	list.addAll(CaseAdvertiseList.stream().collect(Collectors.mapping(CaseAdvertise::getPlace, Collectors.toList())).stream().distinct().collect(Collectors.toList()));
		 	list.stream().forEach(a->{
		 		System.out.println(a.toString()+"======");
		 	});
		 	list.removeIf(i->{
		 		System.out.println(i.toString());
		 		return !i.contains(like);
		 	});
		}
		return list;
	}
*/	
	@MoblieUrl
	@RequestMapping("/add")
	public String add(Model model) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		CaseAdvertiseFileExample example=new CaseAdvertiseFileExample();
		example.setOrderByClause("CREAT_TIME desc");
		if(compId.equals(0)){
			example.createCriteria().andIsDelEqualTo((byte) 0);
		}else{
			example.createCriteria().andIsDelEqualTo((byte) 0).andCompIdEqualTo(compId);
		}
		List<CaseAdvertiseFile> list = caseAdvertiseFileMapper.selectByExample(example);
		
		List<ManageComp> compList=new ArrayList<>();
		ManageCompExample compExample=new ManageCompExample();
		compExample.setOrderByClause("CREATE_TIME desc");
		if(compId.equals(0)){
			compList = manageCompMapper.selectByExample(compExample);
		}else{
			compExample.createCriteria().andCompIdEqualTo(compId);
			compList = manageCompMapper.selectByExample(compExample);
		}
		JSONArray array = new JSONArray();
		list.stream().collect(Collectors.toMap(CaseAdvertiseFile::getFileId, CaseAdvertiseFile::getName))
		.forEach((k,v)->{
			JSONObject jo = new JSONObject();
			jo.put("name", v);
			jo.put("id", k);
			array.add(jo);
		});
		
		ManageCaseExample manageCaseExample = new ManageCaseExample();
		if (compId != 0) {
			manageCaseExample.createCriteria().andCompIdEqualTo(compId);
		}
		// 查询本公司的储物柜列表
		List<ManageCase> selectByExample = manageCaseMapper.selectByExample(manageCaseExample);
		model.addAttribute("compList", compList);
		model.addAttribute("list", array);
		model.addAttribute("caseNoList", selectByExample);
		return request.getAttribute("moblie")+"publishAdd";
	}
	
	
	@SystemControllerLog(description="修改广告")
	@MoblieUrl
	@RequestMapping("/edit")
	public String edit(Model model,Integer fileId) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		CaseAdvertiseFileExample example=new CaseAdvertiseFileExample();
		if(compId.equals(0)){
			example.createCriteria().andIsDelEqualTo((byte) 0);
		}else{
			example.createCriteria().andIsDelEqualTo((byte) 0).andCompIdEqualTo(compId);
		}
		example.setOrderByClause("CREAT_TIME desc");
		List<CaseAdvertiseFile> list = caseAdvertiseFileMapper.selectByExample(example);
		List<EditAdvertiseFileVO>  editList=new ArrayList<>();
		list.stream().forEach(a->{
			EditAdvertiseFileVO editAdvertiseFileVO=new EditAdvertiseFileVO();
			editAdvertiseFileVO.setFileId(a.getFileId());
			editAdvertiseFileVO.setName(a.getName());
			if(fileId.equals(a.getFileId())){
				editAdvertiseFileVO.setFlag((byte) 1);
			}
			editList.add(editAdvertiseFileVO);
		});
		
		
		/*ManageCaseExample manageCaseExample = new ManageCaseExample();
		if (compId != 0) {
			manageCaseExample.createCriteria().andCompIdEqualTo(compId);
		}
		// 查询本公司的储物柜列表
		List<ManageCase> selectByExample = manageCaseMapper.selectByExample(manageCaseExample);
		model.addAttribute("caseNoList", selectByExample);*/
		
		model.addAttribute("list", editList);
		return request.getAttribute("moblie")+"publishEdit";
	}
	/**
	 * @return
	 * 文件上传路径
	 */
	@RequestMapping("/uploadFile")
	public String uploadFile() {
		return "publishEdit";
	}
	/**
	 * @param param
	 * @return
	 * 列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	public LayUiResultJson<CaseAdvertiseVO> list(PageBaseParam param,Integer compIdParam,String like) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<CaseAdvertiseVO> list=new ArrayList<>();
		PageHelper.startPage(param.getPage(), param.getLimit(),true);
		compId = (compId==0)?compIdParam:compId;

		List<CaseAdvertise> advertiseList = caseAdvertiseMapper.selectLikeDes(compId, like); 	// 查询所属公司的广告列表
		PageInfo<CaseAdvertise> pageInfo =new PageInfo<>(advertiseList);
		List<Integer> fileIdList = advertiseList.stream().collect(Collectors.mapping(CaseAdvertise::getFileId, Collectors.toList())).stream().distinct().collect(Collectors.toList());
		//公司list Id
		List<Integer> compIdList = advertiseList.stream().collect(Collectors.mapping(CaseAdvertise::getCompId, Collectors.toList())).stream().distinct().collect(Collectors.toList());
		List<String> caseNoList = advertiseList.stream().collect(Collectors.mapping(CaseAdvertise::getCaseNo, Collectors.toList())).stream().distinct().collect(Collectors.toList());
		
		int i = 1;
		if(!fileIdList.isEmpty()){

			CaseAdvertiseFileExample example=new CaseAdvertiseFileExample();
			example.createCriteria().andFileIdIn(fileIdList); //FILE_ID in (?,?,?,?,?.....)
			List<CaseAdvertiseFile> fileList = caseAdvertiseFileMapper.selectByExample(example); //case_advertise_file 查询出对应的文件列表
			// 以文件Id为键 CaseAdvertiseFile 为值 将一个list转为map
			Map<Integer, CaseAdvertiseFile> CaseAdvertiseFileMap = fileList.stream().collect(Collectors.toMap(CaseAdvertiseFile::getFileId, a->a));
			
			ManageCompExample compExample=new ManageCompExample();
			compExample.createCriteria().andCompIdIn(compIdList); // COMP_ID in (?,?,?,?...)
			List<ManageComp> manageCompList = manageCompMapper.selectByExample(compExample); // 查询出对应的公司信息
			// 以公司id为键，公司名称为值
			Map<Integer, String> compIdMap = manageCompList.stream().collect(Collectors.toMap(ManageComp::getCompId, ManageComp::getCompName));


			ManageCaseExample mcExample=new ManageCaseExample();
			mcExample.createCriteria().andCaseNoIn(caseNoList); // CASE_NO in (?,?,?,?...)
			List<ManageCase> manageCaseList = manageCaseMapper.selectByExample(mcExample); // mac地址（储物柜编号）对应的柜子信息
//			System.out.println(manageCaseList.toString());
			// 以mac为键 商家输入的编号为值
			Map<String, String> mcCaseNoMap = manageCaseList.stream().collect(Collectors.toMap(ManageCase::getCaseNo, ManageCase->ToolsUtils.valueOfStr(ManageCase.getCaseNoBuy())));

			// 遍历广告列表将对应的信息 填充到CaseAdvertiseVo中
			advertiseList.stream().forEach(a->{
				CaseAdvertiseVO caseAdvertiseVO=new CaseAdvertiseVO();
				caseAdvertiseVO.setCompName(compIdMap.get(a.getCompId()));
				caseAdvertiseVO.setCaseNoBuy(mcCaseNoMap.get(a.getCaseNo())); // 商家自己的编号
				caseAdvertiseVO.setAdName(CaseAdvertiseFileMap.get(a.getFileId()).getName()); // 文件名
				caseAdvertiseVO.setCaseNo(a.getCaseNo()); // mac地址
				caseAdvertiseVO.setDes(a.getDes()); // 广告描述
				caseAdvertiseVO.setId(a.getId());
				caseAdvertiseVO.setPlace(a.getPlace());
				caseAdvertiseVO.setFileId(a.getFileId()); // 广告文件的Id
				caseAdvertiseVO.setCreatTime(DateTimeHelper.formatDateTimetoString(a.getCreatTime(), "yyyy-MM-dd HH:mm"));
				list.add(caseAdvertiseVO);
			});
		}
		
		//查询总条数
		long count = pageInfo.getTotal();
		LayUiResultJson<CaseAdvertiseVO> result = new LayUiResultJson<>(count, list);
		return result;
	}
	/**
	 * @param id
	 * @return
	 * 删除
	 */
	@SystemControllerLog(description="删除广告")
	@RequestMapping("/deleteAdvertise")
	@ResponseBody
	public AjaxResult deleteAdvertise(Integer id) {
		try {
			caseAdvertiseMapper.deleteByPrimaryKey(id);
			return new AjaxResult();
		} catch (Exception e) {
			return new AjaxResult("删除失败");
		}
	}
	/**
	 * @param caseAdvertise
	 * @return
	 * 编辑
	 */
	@SystemControllerLog(description="编辑广告")
	@RequestMapping("/updateAdvertise")
	@ResponseBody
	public AjaxResult updateAdvertise(CaseAdvertise caseAdvertise) {
		try {
			System.err.println(caseAdvertise.toString());
			String[] split = caseAdvertise.getCaseNo().split(",");
			CaseAdvertise caseAdvertise2 = caseAdvertise;
			for(int i = 0 ;i< split.length;i++){
				caseAdvertise2.setCaseNo(split[i]);
				caseAdvertiseMapper.updateByPrimaryKeySelective(caseAdvertise2);
			}
			return new AjaxResult();
		} catch (Exception e) {
			return new AjaxResult("修改失败");
		}
	}
	/**
	 * @param caseAdvertise
	 * @return
	 * 添加
	 */
	@SystemControllerLog(description="添加广告")
	@RequestMapping("/addAdvertise")
	@ResponseBody
	public AjaxResult addAdvertise(CaseAdvertise caseAdvertise,String fileIds) {
		String[] split = fileIds.split(",");
		String[] caseNosPlit = caseAdvertise.getCaseNo().split(",");
		System.err.println(caseNosPlit.length+"==="+caseAdvertise.getCaseNo());
		for(int j = 0;j < caseNosPlit.length;j++){
			List<CaseAdvertise> list = new ArrayList<>();
			ManageCaseExample example = new ManageCaseExample();
			example.createCriteria().andCaseNoEqualTo(caseNosPlit[j]);
			List<ManageCase> selectByExample = manageCaseMapper.selectByExample(example);
			String place="";
			if(!selectByExample.isEmpty()) {
				place = selectByExample.get(0).getPlace();
			}
			for(int i=0;i<split.length;i++) {
				CaseAdvertise cad = new CaseAdvertise();
				cad.setFileId(Integer.parseInt(split[i]));
				cad.setCaseNo(caseNosPlit[j]);
				cad.setCompId(caseAdvertise.getCompId());
				cad.setDes(caseAdvertise.getDes());
				cad.setPlace(place);
				cad.setCreatTime(new Date());
				list.add(cad);
			}
			try {
				System.err.println(list.size());
				caseAdvertiseMapper.insertMore(list);
			} catch (Exception e) {
				return new AjaxResult("添加失败");
			}
		}
		return new AjaxResult();
	}

}
